package com.zy.yun.controller.common;

import com.zy.yun.base.common.RestResult;
import com.zy.yun.base.constant.ReturnCodeMsgEnum;
import com.zy.yun.base.util.DateUtil;
import com.zy.yun.base.util.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author : wangyanwei
 * @Date: 2019/4/12 10:31
 * @Description: 图片管理
 */
@Api(description = "图片管理",tags = "图片管理")
@Slf4j
@Controller
@RequestMapping("image")
public class ImageController {


    /**
     *   图片存储路径
     */
    @Value("${image.save-path}")
    private String imageSavePath;

    /**
     * 多长时间创建一个新的文件夹
     */
    @Value("${image.create-dir-days}")
    private Integer imageCreateDirDays;

    /**
     * 图片服务器地址
     */
    @Value("${image.server-addr}")
    private String imageServerAddr;

    /**
     * 功能描述: 以文件流的方式上传图片
     *
     * @auther: wangyanwei
     * @date: 2019/4/12 10:34
     * @param:
     * @return: 图片地址
     */
    @ApiOperation("以文件流的方式上传图片接口")
    @ResponseBody
    @PostMapping("imageUpload")
    public RestResult imageUpload(@RequestParam(value = "file", required = true) MultipartFile file) {

        RestResult restResult = new RestResult();

        if (file.isEmpty()) {
            return RestResult.buildError("图片内容为空！");
        }

        String newFilenameBase = UUIDUtils.random();
        //得到图片后辍
        String originalFileExtension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //文件新名称
        String newFilename = newFilenameBase + originalFileExtension;

        Integer count = DateUtil.getTodateString() != null ? Integer.parseInt(DateUtil.getTodateString()) : 0;
        String dirName = null;
        //根据天数，判断是否需要创建新的目录
        if (count % imageCreateDirDays == 0) {
            dirName = DateUtil.getTodateString();
        } else {
            dirName = DateUtil.getStrDate(String.valueOf(imageCreateDirDays)).replaceAll("-", "");

        }
        String basePath = imageSavePath + "/" + dirName;
        //判断目录是否存在
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs(); //级联创建目录
        }
        //文件路径
        String path = basePath + "/" + newFilename;

        try {
            //写入文件
            file.transferTo(new File(path));
            //拼接前端访问图片全路径
            String imageUrl = imageServerAddr + dirName + "/" + newFilename;

            restResult.setResult(imageUrl);
            restResult.setMsg(ReturnCodeMsgEnum.DATA_SAVE_SUCCESS.getMsg());
            restResult.setCode(ReturnCodeMsgEnum.DATA_SAVE_SUCCESS.getCode());



        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            restResult.setMsg(ReturnCodeMsgEnum.DATA_SAVE_FAIL.getMsg());
            restResult.setCode(ReturnCodeMsgEnum.DATA_SAVE_FAIL.getCode());
        }
        return restResult;
    }


    /**
     * 功能描述: 文件以base64的格式上传
     *
     * @auther: wangyanwei
     * @date: 2019/4/12 14:12
     * @param:
     * @return: 图片地址
     */
    @ApiOperation("文件以base64的格式上传接口")
    @ResponseBody
    @PostMapping("imageUploadBase64")
    public RestResult imageUploadBase64(String file) {

        RestResult restResult = new RestResult();

        if (file.isEmpty()) {
            return RestResult.buildError("图片内容为空！");
        }

        //文件后辍
        //截取第一个 “/” 和 第一个“;” 之前 的内容
        String suffix = "." + file.substring(file.indexOf("/") + 1, file.indexOf(";"));
        //文件新名称
        String newFilenameBase = UUIDUtils.random();
        BASE64Decoder decoder = new BASE64Decoder();

        Integer count = DateUtil.getTodateString() != null ? Integer.parseInt(DateUtil.getTodateString()) : 0;
        String dirName = null;
        //根据天数，判断是否需要创建新的目录
        if (count % imageCreateDirDays == 0) {
            dirName = DateUtil.getTodateString();
        } else {
            dirName = DateUtil.getStrDate(String.valueOf(imageCreateDirDays)).replaceAll("-", "");

        }
        try {

            File destFiledir = new File(imageSavePath + "/" + dirName);
            if (!destFiledir.exists()) {
                destFiledir.mkdirs();// 父目录
            }
            File destFile = new File(imageSavePath + dirName + "/" + newFilenameBase + suffix);
            OutputStream out = new FileOutputStream(destFile);


            //从截取第一个逗号之后的内容
            file = file.substring(file.indexOf(",") + 1, file.length());
            byte[] b = decoder.decodeBuffer(file);
            for (int i = 0; i < b.length; ++i) {
                //调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out.write(b);
            out.close();

            //图片地址全路径
            String imageUrl = imageServerAddr + dirName + "/" + newFilenameBase + suffix;

            restResult.setCode(ReturnCodeMsgEnum.DATA_SAVE_SUCCESS.getCode());
            restResult.setMsg(ReturnCodeMsgEnum.DATA_SAVE_SUCCESS.getMsg());
            restResult.setResult(imageUrl);


        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            restResult.setMsg(ReturnCodeMsgEnum.DATA_SAVE_FAIL.getMsg());
            restResult.setCode(ReturnCodeMsgEnum.DATA_SAVE_FAIL.getCode());

        }
        return restResult;

    }





    /**
     * 功能描述: 获取图片验证码
     * @auther: wangyanwei
     * @date: 2019/4/15 16:14
     * @param:
     * @return:

     */

//    @ApiOperation("获取图片验证码")
//    @GetMapping("api/getImageCaptcha")
//    public void getImageCaptcha(HttpServletRequest request, HttpServletResponse response){
//        CaptchaUtil captchaUtil = new CaptchaUtil();
//        captchaUtil.render(response,request);
//    }
}
